﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using SystemDebug = System.Diagnostics.Debug;

using UnityEngine;


public class StandbyScene : Scene
{
	public static BattleStartMode startMode = BattleStartMode.None;

    #region // 테스트 코드
    int[] nono = new int[4];
    #endregion
    bool isAutoLogin = true;

    enum SceneMode
    {
        BattleReady,
        MemberChange
    }

    const int MaxSelectMemberNum = 4;
    const float CenterListItemStartY = 460.0f;

    SceneMode m_SceneMode = SceneMode.BattleReady;

    #region 씬 전환 애니
    public Animation m_BlurAni;
    public Animation m_TextBattleReady;
    public Animation m_TextMemberChange;
    public UIPanel m_SynergyPanel;
    #endregion

    #region 선택된 4케릭터 UI 관련
    const float ListRootY_up = 513.3f;
    const float ListRootY_down = 210.0f;

    public GameObject m_LeftListRoot;
    Oc_MemberListItem[] m_LeftListItems = new Oc_MemberListItem[4];
    public Animation m_ChangeSceneMode;
    public Animation m_ChangeMember;
    #endregion

    MemberModel m_SelectMember = null;  //뺄 멤버
    MemberModel m_WillChangeMember = null;  //장착할 멤버

    #region 선택안된 멤버들 리스트
    
    public Oc_MemberListItem m_StandardCenterListItem;
    List<int> m_ChangeAbleMembersNo = new List<int>();  // 소팅된 체인지 타겟 멤버들
    List<Oc_MemberListItem> m_CenterListItems = new List<Oc_MemberListItem>();

    public OC_InfoUIWithScroll m_InfoScrollPanel;
    public Animation m_InfoUIAni;
    
    
    // 정렬 관련
    bool m_IsSortMenuOn = false;
    bool IsSortMenuOn
    {
        get { return m_IsSortMenuOn; }
        set
        {
            m_IsSortMenuOn = value;
            MemberListScrollOnOff();
        }
    }
    public Animation m_SortAni;   
    public UILabel[] m_SortKindsLabel;
    SortKind m_SortKind = SortKind.Level;

    string tempString0 = null;
    string tempString1 = null;
    string tempString2 = null;
    #endregion

    public GameObject m_CenterSort;
    public GameObject m_CenterInfo;
    public GameObject m_CenterBlank;

    public UILabel m_SynergyText;

    public UILabel m_SoulStoneNum;

    bool m_IsDescending = true;


    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;

        //NetworkManager.Instance.C2S_MEMBER_CHOICELIST(OnChoiceListCallback);     
        EnterSceneAni(); 
    }

    void OnChoiceListCallback(ResponseModel<List<int>> data)
    {
        if (data.data.Count < MaxSelectMemberNum)
        {
            List<int> nos = UserData.Instance.userModel.m_MemberNoList;
            
            int[] t_Nos = new int[MaxSelectMemberNum];

            for (int i = 0; i < MaxSelectMemberNum; i++)
            {
                t_Nos[i] = nos[i];
            }

            NetworkManager.Instance.C2S_MEMBER_CHOOSE(t_Nos, OnInitMemberChooseCallback);
        }
        else
        {
            UserData.Instance.userModel.choiceMembers = data.data;

            EnterSceneAni();            
        }
    }

    void OnInitMemberChooseCallback(ResponseModel<List<int>> data)
    {
        UserData.Instance.userModel.choiceMembers = data.data;

        EnterSceneAni();
    }

    public override void AwakeScene()
    {
        tempString0 = TextController.GetStringWithId("uiCommonTextLevel");
        tempString1 = TextController.GetStringWithId("uiCommonTextRarityDo");
        tempString2 = TextController.GetStringWithId("uiCommonTextEnhance");

        m_SortKindsLabel[0].text = tempString0;
        m_SortKindsLabel[1].text = tempString1;
        m_SortKindsLabel[2].text = tempString2;

        Transform tempItem = null;
        Vector3 pos = Vector3.zero;

        for (int i = 0; i < m_LeftListItems.Length; i++)
        {
            tempItem = m_LeftListRoot.transform.Find(string.Format("memberList_change{0}", i));
            pos = tempItem.localPosition;
            pos.x = -1200.0f;
            tempItem.localPosition = pos;
            m_LeftListItems[i] = tempItem.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
        }


        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "hshshs", string.Empty, OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {   
            EnterSceneAni();
        }        
    }

    public override void StartScene()
    {
        SetActiveHelpButton(false);
    }

    //public override void UpdateScene()
    //{
    //}

    void UpdateLeftListItems()      // 씬모드 바뀔때만 한번 동작
    {

        int selectIndex = 0;
        if (m_SelectMember != null)
        {
            foreach(Oc_MemberListItem t in m_LeftListItems)
            {
                if (m_SelectMember.no == t.m_MemberModel.no)
                    break;

                selectIndex++;
            }            
        }


        int i = 0;
        foreach(MemberModel member in UserData.Instance.userModel.m_ChoiceMemberList)
        {           
			if(i>=4)
				break;//일단 임시로 4명초과 되는 상황 막자..//
            m_LeftListItems[i].SetList(member);

            if (m_SceneMode == SceneMode.BattleReady)
            {
                m_LeftListItems[i].SetOn(false);
            }
            else
            {
                if (m_SelectMember != null)
                { 
                    if(member.no == m_SelectMember.no)  // 기존선택 반영
                    {
                        m_LeftListItems[i].SetOn(false);
                        m_SelectMember = m_LeftListItems[i].m_MemberModel;
                    }
                    else
                        m_LeftListItems[i].SetOff();
                }
                else
                {
                    if (i == 0)
                    {
                        m_LeftListItems[i].SetOn(false);
                        m_SelectMember = m_LeftListItems[i].m_MemberModel;
                    }
                    else
                        m_LeftListItems[i].SetOff();
                }              
            }
            i++;
        }

        if(m_SceneMode == SceneMode.BattleReady)
            SetCharacterModel();     


        if(UserData.Instance.userModel.m_PartySincSuccessList.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < UserData.Instance.userModel.m_PartySincSuccessList.Count; j++)
            {
                sb.Append(TextController.GetStringWithId(string.Format("partySync{0}", UserData.Instance.userModel.m_PartySincSuccessList[j].syncID)));
                if (j < UserData.Instance.userModel.m_PartySincSuccessList.Count - 1)
                    sb.Append("| ");
                if (j % 3 == 2 && UserData.Instance.userModel.m_PartySincSuccessList.Count/3 - 1 > j/3)
                    sb.Append("\n");
            }
            m_SynergyText.text = sb.ToString();
        }
        else
        {
            m_SynergyText.text = TextController.GetStringWithId("uiStandbyCaution1");
        }
    }
    
    void UpdateCenterListItems()
    {
        SortMember();

        int listNum = m_ChangeAbleMembersNo.Count;

        if(listNum > 0)
        {
            m_CenterSort.SetActive(true);
            m_CenterBlank.SetActive(false);
            m_CenterInfo.SetActive(true);

            Oc_MemberListItem tempOc = null;
            GameObject tempOb = null;

            for (int i = 0; i < listNum; i++)
            {
                if (i >= m_CenterListItems.Count)
                {
                    if (i == 0)
                    {
                        tempOc = m_StandardCenterListItem;
                        m_CenterListItems.Add(tempOc);
                    }
                    else
                    {
                        tempOb = Instantiate(m_StandardCenterListItem.gameObject) as GameObject;
                        tempOc = tempOb.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
                        m_CenterListItems.Add(tempOc);
                    }

                    tempOc.transform.parent = m_StandardCenterListItem.transform.parent;
                    tempOc.transform.localScale = m_StandardCenterListItem.transform.localScale;

                    Vector3 pos = m_StandardCenterListItem.transform.localPosition;
                    pos.y = CenterListItemStartY - (i * 220.0f);
                    tempOc.transform.localPosition = pos;
                }

                m_CenterListItems[i].name = string.Format("CenterList_{0}", i);
                m_CenterListItems[i].SetList(UserData.Instance.userModel.members_dic[m_ChangeAbleMembersNo[i].ToString()]);
                m_CenterListItems[i].gameObject.SetActive(true);
            }

            for (int i = listNum; i < m_CenterListItems.Count; i++)
            {
                m_CenterListItems[i].gameObject.SetActive(false);
            }


            // 무조건 1번째 멤버 선택하여 보여줌
            foreach (Oc_MemberListItem t_ML in m_CenterListItems)
            {
                t_ML.SetOff();
            }

            if (m_CenterListItems.Count > 0)
            {
                if (m_WillChangeMember == null)
                {
                    m_CenterListItems[0].SetOn(false);
                    m_WillChangeMember = m_CenterListItems[0].m_MemberModel;
                }
                else
                {
                    int index = 0;
                    foreach(Oc_MemberListItem t in m_CenterListItems)
                    {
                        if(t.m_MemberModel.no == m_WillChangeMember.no)
                            break;                        
                        index++;
                    }
                    m_CenterListItems[index].SetOn(false);
                    m_WillChangeMember = m_CenterListItems[index].m_MemberModel;
                }
               
                UpdateInfoUI(m_WillChangeMember);
                m_InfoUIAni.gameObject.SetActive(true);
            }
            else
            {
                m_InfoUIAni.gameObject.SetActive(false);
            }
        }
        else
        {
            m_StandardCenterListItem.gameObject.SetActive(false);
            m_CenterSort.SetActive(false);
            m_CenterBlank.SetActive(true);
            m_CenterInfo.SetActive(false);
        }
    }

    void MemberListScrollOnOff()
    {
        foreach (Oc_MemberListItem item in m_CenterListItems)
        {
            UIDragScrollView sv = item.GetComp("UIDragScrollView") as UIDragScrollView;
            sv.enabled = !IsSortMenuOn;
        }
    }


    void UpdateInfoUI(MemberModel tempModel)
    {
        OC_InfoUIWithScroll.instance.UpdateInfoUI(tempModel);
        OC_InfoUIWithScroll.instance.m_SelectListNum = -1;
        OC_InfoUIWithScroll.instance.MoveList();
    }


    void SortMember()
    {
        m_ChangeAbleMembersNo.Clear();

        List<MemberModel> tList = new List<MemberModel>();

        foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
        {
            bool isChoiceMember = false;
            foreach (int no in UserData.Instance.userModel.choiceMembers)
            {
                if (no == t.Value.no)
                {
                    isChoiceMember = true;
                    break;
                }
            }

            if (!isChoiceMember)            
                tList.Add(t.Value);
        }

        int max = tList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case SortKind.Level:
                        {
                            if (tList[j].level < tList[j + 1].level)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Rare:
                        {
                            if (tList[j].rarity < tList[j + 1].rarity)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Inhance:
                        {
                            if (tList[j].strengthening < tList[j + 1].strengthening)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                }
            }
        }

        for (int i = 0; i < max; i++)
        {
            if (m_IsDescending)
                m_ChangeAbleMembersNo.Add(tList[i].no);
            else
                m_ChangeAbleMembersNo.Add(tList[max - i - 1].no);
        }
    }


    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {      
        if (collider.name.Contains("memberList_change"))
        {
            if (m_SceneMode == SceneMode.MemberChange)
            {
                Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;

                foreach (Oc_MemberListItem t_ML in m_LeftListItems)
                {
                    if (t_ML.Equals(Choise_ML))
                    {
                        t_ML.SetOn(true);
                        m_SelectMember = Choise_ML.m_MemberModel;
                    }
                    else
                        t_ML.SetOff();
                }
            }
        }
        else if(collider.name.Contains("CenterList_"))
        {
            if (m_SceneMode == SceneMode.MemberChange)
            {
                Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;

                foreach (Oc_MemberListItem t_ML in m_CenterListItems)
                {
                    if (t_ML.Equals(Choise_ML))
                    {
                        t_ML.SetOn(true);
                        m_WillChangeMember = Choise_ML.m_MemberModel;                       
                        UpdateInfoUI(m_WillChangeMember);
                    }
                    else
                        t_ML.SetOff();
                }
            }
        }
        else if (collider.gameObject.name.Contains("Button_Sort_"))
        {
            if (IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_close");
            }
            else
            {
                m_SortAni.Play("sort_open");
            }
            IsSortMenuOn = !IsSortMenuOn;
        }       

        switch (collider.name)
        {
            case "Button_GoChange":
                if(m_SceneMode == SceneMode.BattleReady)
                    GoMemberChange();
                break;
            case "Button_GoBattle":
                if (m_SceneMode == SceneMode.BattleReady)
                    //SceneController.LoadLevel("Friend Battle");
                    // 2 - A : 일일 PVP 일 경우
                    if (UserData.Instance.isQuickPVPBattle && UserData.Instance.counterAttackMsgId == 0)
                        StartBattleQuickPVP();

                    else if (UserData.Instance.counterAttackMsgId > 0)
                        StartBattleCounterAttack();

                    // 2 - C : 레이드 보스 전투일 경우
                    else if (UserData.Instance.raidBossId != 0)
                        NetworkManager.Instance.C2S_START_RAIDBOSS_BATTLE(ResponseStartRaidBossBattle, 0);

                    // 2 - D : 그 이외의 전투일 경우
                    else
                    {
                        // 2 - D - (1) : 조사
                        if (StandbyScene.startMode == BattleStartMode.Research)
                            NetworkManager.Instance.C2S_SEND_TO_RESEARCH(ResponseResearch, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.choiceMembers.ToArray());

                        // 2 - D - (2) : 확장전
                        else if (StandbyScene.startMode == BattleStartMode.ExpansionWar)
                            NetworkManager.Instance.C2S_SEND_TO_EXPANSION(ResponseExpansion, WorldSceneManager.GetSelectedAreaId(), UserData.Instance.userModel.regions.expansionWarStep == 0 ? 1 : (int)UserData.Instance.userModel.regions.expansionWarStep, UserData.Instance.userModel.choiceMembers.ToArray());
                    }
                break;
            case "Button_Change":
                GoBattleReady();
                break;
            case "Button_ChangeMember":
                {
                    if (m_SelectMember != null && m_WillChangeMember != null)
                    {
                        int index = UserData.Instance.userModel.choiceMembers.IndexOf(m_SelectMember.no);
                        UserData.Instance.userModel.choiceMembers[index] = m_WillChangeMember.no;

                        MemberModel temp = m_WillChangeMember;  // 이후 리스트 업데이트 할때 필요
                        m_WillChangeMember = m_SelectMember;
                        m_SelectMember = temp;

                        int[] nos = UserData.Instance.userModel.choiceMembers.ToArray();
                        NetworkManager.Instance.C2S_MEMBER_CHOOSE(nos, OnMemberChooseCallback);
                    }
                }
                break;
            case "Button_updown":
                {
                    m_IsDescending = !m_IsDescending;

                    collider.transform.Find("Up").gameObject.SetActive(!m_IsDescending);
                    collider.transform.Find("Down").gameObject.SetActive(m_IsDescending);

                    SetSortMenuUI(m_SortKind);
                }
                break;
            case "Button_Sort":
                {
                    if (IsSortMenuOn)
                        m_SortAni.Play("sort_close");
                    else
                        m_SortAni.Play("sort_open");

                    IsSortMenuOn = !IsSortMenuOn;
                }
                break;
            case "synergy":
                if(UserData.Instance.userModel.m_PartySincSuccessList.Count > 0)        // 싱크로 1개 이상일때 팝업 띄움
                    PopupManager.PushPopup(PopupKind.CharacterEffect);
                break;
        }
    }

    void OnMemberChooseCallback(ResponseModel<List<int>> data)
    {
        UserData.Instance.userModel.choiceMembers = data.data;
        UpdateLeftListItems();
        UpdateCenterListItems();        
    }


    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = (SortKind)(((int)m_SortKind + num) % 3);   // 각 상황마다 대응

        SetSortMenuUI(m_SortKind);
    }

    void SetSortMenuUI(SortKind sortKind)        // 소트 메뉴 라벨 설정
    {       
        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        UpdateCenterListItems();
    }

    public override void BackButton()
    {
        switch (m_SceneMode)
        {
            case SceneMode.BattleReady:
                {
                    //4케릭터 캐쉬 삭제

                    ResourceManager.Inst.ClearAllChoiceModel();                    
                    
                    UserData.Instance.raidBossId = 0;
					UserData.Instance.raidBossStartData = null;
					UserData.Instance.raidBossResultData = null;
					UserData.Instance.raidBossModel = null;

					UserData.Instance.researchResultData = null;
					UserData.Instance.expansionWarResultData = null;
					UserData.Instance.quickPvPResultData = null;
					UserData.Instance.quickPVPUserModel = null;

					WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
					WorldSceneManager.sentResearchAreaId = 0;

                    if (startMode == BattleStartMode.Research || startMode == BattleStartMode.RaidBossFromResearch)
                        SceneController.LoadLevel("World");
					else if(startMode == BattleStartMode.ExpansionWar)
                        SceneController.LoadLevel("Expansion");
					else if (startMode == BattleStartMode.QuickPvP)
                        SceneController.LoadLevel("Main");
					else if (startMode == BattleStartMode.RaidBoss)
                        SceneController.LoadLevel("Main");
                }
                //SceneController.LoadPreLevel();
                break;
            case SceneMode.MemberChange:
                GoBattleReady();
                break;
        }
    }

    void GoBattleReady()
    {
        m_SceneMode = SceneMode.BattleReady;

        TweenAlpha ta = TweenAlpha.Begin(m_SynergyPanel.gameObject, 1.0f, 1.0f);
        ta.delay = 0.5f;

        m_SynergyPanel.collider.enabled = true;

        m_TextBattleReady.Play("lobby_text in");
        m_TextBattleReady.Play("lobby_text idle",AnimationPlayMode.Queue);
        m_TextMemberChange.Play("lobby_text out");
        m_BlurAni.Play("lobby-member_change out");
        m_ChangeSceneMode.Play("lobby_UI_IN");
        m_ChangeMember.Play("change_member out");
        iTween.MoveTo(m_LeftListRoot, iTween.Hash("islocal", true, "y", ListRootY_down, "time", 0.2f, "easetype", "spring", "delay", 0.2f));

        UpdateLeftListItems();
    }

    void GoMemberChange()
    {
        m_SceneMode = SceneMode.MemberChange;

        TweenAlpha ta = TweenAlpha.Begin(m_SynergyPanel.gameObject, 1.0f, 0.0f);
        ta.delay = 0.5f;
        m_SynergyPanel.collider.enabled = false;

        m_TextMemberChange.Play("lobby_text in");
        m_TextMemberChange.Play("lobby_text idle", AnimationPlayMode.Queue);
        m_TextBattleReady.Play("lobby_text out");
        m_BlurAni.Play("lobby-member_change in");
        m_ChangeSceneMode.Play("lobby_UI to member");
        m_ChangeMember.Play("change_member in");
        iTween.MoveTo(m_LeftListRoot, iTween.Hash("islocal", true, "y", ListRootY_up, "time", 0.2f, "easetype", "spring", "delay", 0.8f));

        UpdateLeftListItems();
        UpdateCenterListItems();
    }


    void EnterSceneAni()
    {
        m_SoulStoneNum.text = string.Format("[525252]x[-]{0}", UserData.Instance.userModel.SoulStone);

        StartCoroutine("EnterSceneAniWithDelay", 0.0f);
    }


    IEnumerator EnterSceneAniWithDelay(float time)
    {
        yield return new WaitForSeconds(time);

        m_SceneMode = SceneMode.BattleReady;
        m_SynergyPanel.alpha = 0.0f;
        TweenAlpha ta = TweenAlpha.Begin(m_SynergyPanel.gameObject, 1.0f, 1.0f);
        ta.delay = 0.5f;

        m_SynergyPanel.collider.enabled = true;

        m_TextBattleReady.Play("lobby_text in");
        m_TextBattleReady.Play("lobby_text idle", AnimationPlayMode.Queue);
        m_BlurAni.Play("lobby-member_change out");
        m_ChangeSceneMode.Play("lobby_UI_IN");

        for (int i = 0; i < m_LeftListItems.Length; i++)
        {
            iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -471.1329f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f) + 0.3f));
        }

        UpdateLeftListItems();
    }

    // 동적 케릭터 모델 관리
    GameObject m_3DPosition = null;
	BattleCharInfo[] m_3DModelInfos = new BattleCharInfo[4];

    GameObject[] m_3DModels = new GameObject[4];

    public override void OnWillDestroy()
	{
		Debug.Log("standby scene OnWillDestroy");
		ResourceManager.Inst.RetainChoiceMemberGo();
	}

	
	void SetCharacterModel() 
    {
        if(m_3DPosition == null)        
            m_3DPosition = GameObject.Find("LobbyVersion/Position");
        
		//ResourceManager.Inst.ClearChoiceMemberModel();
        for (int i = 0; i < UserData.Instance.userModel.m_ChoiceMemberList.Count; i++)
        {
			if(i>=4)
				break;//일단 임시로 4명초과 되는 상황 막자..//

            string modelName = GameData.Inst.ModelDefineDic[UserData.Instance.userModel.m_ChoiceMemberList[i].model];

            if (m_3DModels[i] != null && m_3DModels[i].name.Equals(modelName))  // 같은 위치 케릭터면 이전 케릭터 재사용
            {
				//ResourceManager.Inst.AddChoiceMemberModel( m_3DModels[i]);
                continue;
            }
            else if (m_3DModels[i] != null) {
				ResourceManager.Inst.RemoveChoiceModel(m_3DModels[i]);
				Destroy(m_3DModels[i]);
			}

			int modelID = UserData.Instance.userModel.m_ChoiceMemberList[i].model;
			m_3DModels[i] = ResourceManager.Inst.GetChoiceMemberGo(modelID);
			if(m_3DModels[i]==null) {
				m_3DModels[i] = BattleResManager.CreatePawn(modelID, false);
				ResourceManager.Inst.AddChoiceMemberGo(modelID, m_3DModels[i]);
			}
            SystemDebug.Assert(m_3DModels[i]);
            m_3DModels[i].name = modelName;

			Transform root = m_3DPosition.transform.Find(string.Format("{0:00}", 4 - i));
			
            
            
            //string model_no = MyUtil.FindClassWithModelName(modelName);

            int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
            string model_no = modelName;
            bool isHaveUnderBar = (nRemoveIndex != -1);
            
            
            for (int j = 0; j < root.childCount; j++)
            {
                bool isCorrectRoot = false;
                if (isHaveUnderBar)
                {
                    string rootName = root.GetChild(j).name.Remove(4);
                    string childName = model_no.Remove(4);
                    isCorrectRoot = rootName.Equals(childName);
                }
                else    // 언더바 안들은 애들은 이전 방식으로 찾는다
                {
                    string rootName = root.GetChild(j).name;
                    string childName = model_no;
                    isCorrectRoot = rootName.Contains(childName);
                }

                if (isCorrectRoot)               
                //if( root.GetChild( j ).name.Contains( model_no ) )
                {
                    m_3DModels[i].transform.parent = root.GetChild(j);
                    m_3DModels[i].transform.localScale = Vector3.one;
                    m_3DModels[i].transform.localPosition = Vector3.zero;
                    m_3DModels[i].transform.localRotation = Quaternion.Euler(Vector3.zero);
                    break;
                }
            }

            Animation ani = m_3DModels[i].GetComponent<Animation>();
	        SystemDebug.Assert( ani );

            int num = 0;
            if (ani.GetClip("lobby02") != null)
            {
                System.Random rand = new System.Random();
                num = rand.Next(0, 1);
            }

            ani["lobby01"].clip.wrapMode = WrapMode.Loop;
            ani["lobby02"].clip.wrapMode = WrapMode.Loop;

            if(num == 0)
                ani.Play("lobby01");
            else
                ani.Play("lobby02");


            m_3DModelInfos[i] = AttachWeapon(UserData.Instance.userModel.m_ChoiceMemberList[i], m_3DModels[i]);
        }        
    }

    //봉혼석 체크 박스 온오프 리시버
    void OnCheckBoxButton(EPCheckBox box)
    {        
        UserData.Instance.m_IsUseSoulStone = box.IsChecked;

        for (int i = 0; i < m_3DModelInfos.Length; i++)
        {
            if (m_3DModelInfos[i] == null)
                continue;

            string[] attachName = new string[2] { m_3DModelInfos[i].R_Weapon_AttachName, m_3DModelInfos[i].L_Weapon_AttachName };

            for (int j = 0; j < attachName.Length ; j++)
            {
                Transform child = m_3DModelInfos[i].transform.FindChild(attachName[j]);
                if (child != null)
                {
                    if (child.GetChild(0) != null)
                    {
                        Transform eff = child.GetChild(0).Find("powershard");
                        if (eff != null)
                            eff.gameObject.SetActive(box.IsChecked);
                    }
                }
            }
        }
    }



    public static Dictionary<string, GameObject> weaponPrefabDic = new Dictionary<string, GameObject>();

    public BattleCharInfo AttachWeapon(MemberModel member, GameObject _parent)
    {

        int[] itemModelId = new int[2];

        if (member.rightItem != null)
            itemModelId[0] = member.rightItem.itemInfo.modelID;


        if (member.leftItem != null)
            itemModelId[1] = member.leftItem.itemInfo.modelID;

        BattleCharInfo charInfo = _parent.GetComponent("BattleCharInfo") as BattleCharInfo;

        BattleResManager.AttachWeapon(_parent, charInfo, itemModelId, false);

        return charInfo;
    }


    public override void HelpButton()
    {
        switch (m_SceneMode)
        {
            case SceneMode.MemberChange:
                {
                    Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
                    pt.SetPopupWithTutorialKind(TutorialKind.helpCharChangeInfo);
                }
                break;
            case SceneMode.BattleReady:
                {
                    Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
                    pt.SetPopupWithTutorialKind(TutorialKind.helpStandbyInfo);
                }
                break;
        }        
    }

	public override void HomeButton()
	{
        //4케릭터 캐쉬 삭제

        ResourceManager.Inst.ClearAllChoiceModel();

        UserData.Instance.raidBossId = 0;
        UserData.Instance.raidBossStartData = null;
        UserData.Instance.raidBossResultData = null;
        UserData.Instance.raidBossModel = null;

        UserData.Instance.expansionWarResultData = null;
        UserData.Instance.quickPvPResultData = null;
        UserData.Instance.quickPVPUserModel = null;

        WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
        WorldSceneManager.sentResearchAreaId = 0;
        UserData.Instance.researchResultData = null;

        StandbyScene.startMode = BattleStartMode.None;

		base.HomeButton ();
	}

    void GetQuestInfo()
    {
        NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
    }

    public void StartBattleQuickPVP(long[] friendInfo = null)
    {
       // EPLog.Log("StartBattleQuickPVP : " + friendInfo);
        NetworkManager.Instance.C2S_QUICK_START(UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo, (responseData) =>
        {
            if (responseData.ecode != 0)
            {
                Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(responseData.ecode))));
                return;
            }

            if (responseData.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in responseData.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            Invoke("GetQuestInfo", 0.5f);

            // 빠른 PVP 상대의 UserModel 설정
            UserData.Instance.quickPVPUserModel = responseData.data;

            SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01"); // Battle_4vs4_Heights_Verteron_01
        });
    }

    public void StartBattleCounterAttack(long[] friendInfo = null)
    {
        //EPLog.Log("StartBattleCounterAttack : " + friendInfo);
        NetworkManager.Instance.C2S_QUICK_START_IV(UserData.Instance.userModel.choiceMembers.ToArray(), friendInfo, UserData.Instance.counterAttackMsgId, (responseData) =>
        {
            if (responseData.ecode != 0)
            {
                Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(responseData.ecode))));
                return;
            }

            if (responseData.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in responseData.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            Invoke("GetQuestInfo", 0.5f);

            // 빠른 PVP 상대의 UserModel 설정
            UserData.Instance.quickPVPUserModel = responseData.data;

            SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01"); // Battle_4vs4_Heights_Verteron_01
        });
    }

    #region - 응답 처리
    private void ResponseStartRaidBossBattle(ResponseModel<RaidBossStartModel> result)
    {
        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }

        if (result.responseResult.completeIdList.Count != 0)
        {
            foreach (int id in result.responseResult.completeIdList)
            {
                ToastManager.Instance.ShowAchievementCompleteToast(id, true);
            }
        }

        Invoke("GetQuestInfo", 0.5f);

        StandbyScene.startMode = BattleStartMode.None;
        //		if( WorldSceneManager.isSentSearch )
        //		{
        //			WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
        //			WorldSceneManager.sentResearchAreaId = 0;
        //			UserData.Instance.researchResultData = null;
        //		}
        UserData.Instance.raidBossStartData = result.data;
        UserData.Instance.battleRandomSeed = result.data.seed;

        // 다대다전투 - 레이드 임시로 Battle_Raid_Tiamats_01만 사용.
        SceneController.LoadLevel("Battle_Raid_Tiamats_01");

        //if( result.data.raidBossId == 10001 )
        //	SceneController.LoadLevel("Battle_Boss_Tiamats_01");
        //else
        //	SceneController.LoadLevel("Battle_Boss_Beshmundir_01");
    }

    private void ResponseQuickPvp(ResponseModel<UserModel> result)
    {
        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }

        if (result.responseResult.completeIdList.Count != 0)
        {
            foreach (int id in result.responseResult.completeIdList)
            {
                ToastManager.Instance.ShowAchievementCompleteToast(id, true);
            }
        }

        Invoke("GetQuestInfo", 0.5f);

        StandbyScene.startMode = BattleStartMode.None;
        Debug.Log("ResponseQuickPvp ecode=" + result.ecode);
        if (result.ecode != 0)
            return;
        UserData.Instance.battleRandomSeed = UnityEngine.Random.Range(1, 10000);//임시//
        WorldSceneManager.isSentSearch = false;
        SceneController.LoadLevel("Battle_4vs4_Forest_Poeta_01");
    }

    public void ResponseResearch(ResponseModel<ResearchStartModel> result)
    {
        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }

        if (result.responseResult.completeIdList.Count != 0)
        {
            foreach (int id in result.responseResult.completeIdList)
            {
                ToastManager.Instance.ShowAchievementCompleteToast(id, true);
            }
        }


        Invoke("GetQuestInfo", 0.5f);
        StandbyScene.startMode = BattleStartMode.None;
        UserData.Instance.battleRandomSeed = result.data.seed;
        WorldSceneManager.isSentSearch = true;
        WorldSceneManager.sentResearchAreaId = WorldSceneManager.GetSelectedAreaId();
		UserData.Instance.investigateNpcNo = result.data.npcNo;
        SceneController.LoadLevel(SceneController.GetCurrentBattleSceneName(WorldSceneManager.GetSelectedAreaId()));
    }

    public void ResponseExpansion(ResponseModel<ExpansionWarStartModel> result)
    {
        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }

        if (result.responseResult.completeIdList.Count != 0)
        {
            foreach (int id in result.responseResult.completeIdList)
            {
                ToastManager.Instance.ShowAchievementCompleteToast(id, true);
            }
        }

        Invoke("GetQuestInfo", 0.5f);
        StandbyScene.startMode = BattleStartMode.None;
        UserData.Instance.battleRandomSeed = UnityEngine.Random.Range(1, 10000);//임시//
        UserData.Instance.extendWarWave1 = result.data.wave1;
        UserData.Instance.extendWarWave2 = result.data.wave2;
        UserData.Instance.extendWarWave3 = result.data.wave3;
        WorldExtensionBattleStageScene.isExpansionWar = true;
        SceneController.LoadLevel(SceneController.GetCurrentBattleSceneName(WorldSceneManager.GetSelectedAreaId()));
    }
    #endregion
}